import { DorisConnector, DorisConnectionConfig, QueryResult, TableSchema, DatabaseSchema } from './DorisConnector';
import { IConnection } from '../models/Connection';
import { connectionModel } from '../models';

export interface ConnectionPoolStats {
  connectionId: string;
  connectionName: string;
  isActive: boolean;
  isHealthy: boolean;
  poolStatus: {
    totalConnections: number;
    activeConnections: number;
    idleConnections: number;
    queuedRequests: number;
  };
  lastHealthCheck: Date;
}

export class DorisConnectionManager {
  private static instance: DorisConnectionManager;
  private connectors: Map<string, DorisConnector> = new Map();
  private healthCheckInterval: NodeJS.Timeout | null = null;
  private readonly HEALTH_CHECK_INTERVAL = 60000; // 1分钟

  private constructor() {
    this.startHealthCheck();
  }

  // 单例模式
  public static getInstance(): DorisConnectionManager {
    if (!DorisConnectionManager.instance) {
      DorisConnectionManager.instance = new DorisConnectionManager();
    }
    return DorisConnectionManager.instance;
  }

  // 创建连接器
  private async createConnector(connection: IConnection): Promise<DorisConnector> {
    // 解密密码
    const decryptedPassword = await this.decryptPassword(connection.password_encrypted);
    
    const config: DorisConnectionConfig = {
      host: connection.host,
      port: connection.port,
      user: connection.username,
      password: decryptedPassword,
      database: connection.database_name || undefined,
      ssl: connection.ssl_enabled ? {} : undefined,
      timeout: connection.timeout,
      connectionLimit: connection.max_connections,
      acquireTimeout: connection.timeout + 10000 // 获取连接超时时间比查询超时时间多10秒
    };

    return new DorisConnector(config);
  }

  // 获取连接器
  async getConnector(connectionId: string): Promise<DorisConnector> {
    // 检查缓存中是否存在
    if (this.connectors.has(connectionId)) {
      const connector = this.connectors.get(connectionId)!;
      
      // 检查连接是否健康
      const isHealthy = await connector.isHealthy();
      if (isHealthy) {
        return connector;
      } else {
        // 连接不健康，移除并重新创建
        await connector.close();
        this.connectors.delete(connectionId);
      }
    }

    // 从数据库获取连接配置
    const connection = await connectionModel.getConnectionForAuth(connectionId);
    if (!connection) {
      throw new Error(`连接不存在: ${connectionId}`);
    }

    if (!connection.is_active) {
      throw new Error(`连接已被禁用: ${connection.name}`);
    }

    // 创建新的连接器
    const connector = await this.createConnector(connection);
    this.connectors.set(connectionId, connector);

    return connector;
  }

  // 测试连接
  async testConnection(connectionId: string): Promise<{
    success: boolean;
    message: string;
    responseTime?: number;
    serverVersion?: string;
    errorDetails?: string;
  }> {
    try {
      const connector = await this.getConnector(connectionId);
      return await connector.testConnection();
    } catch (error: any) {
      return {
        success: false,
        message: '获取连接失败',
        errorDetails: error.message
      };
    }
  }

  // 执行查询
  async executeQuery(connectionId: string, sql: string, params: any[] = []): Promise<QueryResult> {
    const connector = await this.getConnector(connectionId);
    return await connector.executeQuery(sql, params);
  }

  // 获取数据库列表
  async getDatabases(connectionId: string): Promise<string[]> {
    const connector = await this.getConnector(connectionId);
    return await connector.getDatabases();
  }

  // 获取表列表
  async getTables(connectionId: string, database?: string): Promise<Array<{
    table_name: string;
    table_type: string;
    table_comment: string;
  }>> {
    const connector = await this.getConnector(connectionId);
    return await connector.getTables(database);
  }

  // 获取表结构
  async getTableSchema(connectionId: string, tableName: string, database?: string): Promise<TableSchema> {
    const connector = await this.getConnector(connectionId);
    return await connector.getTableSchema(tableName, database);
  }

  // 获取数据库结构
  async getDatabaseSchema(connectionId: string, database?: string): Promise<DatabaseSchema> {
    const connector = await this.getConnector(connectionId);
    return await connector.getDatabaseSchema(database);
  }

  // 执行事务
  async executeTransaction(connectionId: string, queries: Array<{ sql: string; params?: any[] }>): Promise<QueryResult[]> {
    const connector = await this.getConnector(connectionId);
    return await connector.executeTransaction(queries);
  }

  // 获取所有连接池状态
  async getAllConnectionStats(): Promise<ConnectionPoolStats[]> {
    const stats: ConnectionPoolStats[] = [];
    
    // 获取所有活跃连接
    const activeConnections = await connectionModel.getActiveConnections();
    
    for (const connection of activeConnections) {
      let poolStatus = {
        totalConnections: 0,
        activeConnections: 0,
        idleConnections: 0,
        queuedRequests: 0
      };
      
      let isHealthy = false;
      
      // 如果连接器存在，获取池状态和健康状态
      if (this.connectors.has(connection.id)) {
        const connector = this.connectors.get(connection.id)!;
        poolStatus = connector.getPoolStatus();
        isHealthy = await connector.isHealthy();
      }
      
      stats.push({
        connectionId: connection.id,
        connectionName: connection.name,
        isActive: connection.is_active,
        isHealthy,
        poolStatus,
        lastHealthCheck: new Date()
      });
    }
    
    return stats;
  }

  // 关闭指定连接
  async closeConnection(connectionId: string): Promise<void> {
    if (this.connectors.has(connectionId)) {
      const connector = this.connectors.get(connectionId)!;
      await connector.close();
      this.connectors.delete(connectionId);
      console.log(`连接已关闭: ${connectionId}`);
    }
  }

  // 关闭所有连接
  async closeAllConnections(): Promise<void> {
    const closePromises = Array.from(this.connectors.entries()).map(async ([id, connector]) => {
      try {
        await connector.close();
        console.log(`连接已关闭: ${id}`);
      } catch (error) {
        console.error(`关闭连接失败 ${id}:`, error);
      }
    });
    
    await Promise.all(closePromises);
    this.connectors.clear();
    
    if (this.healthCheckInterval) {
      clearInterval(this.healthCheckInterval);
      this.healthCheckInterval = null;
    }
  }

  // 重新加载连接配置
  async reloadConnection(connectionId: string): Promise<void> {
    await this.closeConnection(connectionId);
    // 下次使用时会自动重新创建
  }

  // 批量测试连接
  async testMultipleConnections(connectionIds: string[]): Promise<Array<{
    connectionId: string;
    connectionName: string;
    testResult: {
      success: boolean;
      message: string;
      responseTime?: number;
      serverVersion?: string;
      errorDetails?: string;
    };
  }>> {
    const results = [];
    
    for (const connectionId of connectionIds) {
      const connection = await connectionModel.getConnectionById(connectionId);
      const testResult = await this.testConnection(connectionId);
      
      results.push({
        connectionId,
        connectionName: connection?.name || '未知连接',
        testResult
      });
    }
    
    return results;
  }

  // 获取连接健康状态摘要
  async getHealthSummary(): Promise<{
    totalConnections: number;
    activeConnections: number;
    healthyConnections: number;
    unhealthyConnections: number;
    connectionsWithIssues: Array<{
      connectionId: string;
      connectionName: string;
      issue: string;
    }>;
  }> {
    const stats = await this.getAllConnectionStats();
    
    const totalConnections = stats.length;
    const activeConnections = stats.filter(s => s.isActive).length;
    const healthyConnections = stats.filter(s => s.isHealthy).length;
    const unhealthyConnections = stats.filter(s => s.isActive && !s.isHealthy).length;
    
    const connectionsWithIssues = stats
      .filter(s => s.isActive && !s.isHealthy)
      .map(s => ({
        connectionId: s.connectionId,
        connectionName: s.connectionName,
        issue: '连接不健康'
      }));
    
    return {
      totalConnections,
      activeConnections,
      healthyConnections,
      unhealthyConnections,
      connectionsWithIssues
    };
  }

  // 启动健康检查
  private startHealthCheck(): void {
    this.healthCheckInterval = setInterval(async () => {
      try {
        await this.performHealthCheck();
      } catch (error) {
        console.error('健康检查失败:', error);
      }
    }, this.HEALTH_CHECK_INTERVAL);
  }

  // 执行健康检查
  private async performHealthCheck(): Promise<void> {
    const connectorIds = Array.from(this.connectors.keys());
    
    for (const connectionId of connectorIds) {
      try {
        const connector = this.connectors.get(connectionId);
        if (!connector) continue;
        
        const isHealthy = await connector.isHealthy();
        if (!isHealthy) {
          console.warn(`连接不健康，将被移除: ${connectionId}`);
          await connector.close();
          this.connectors.delete(connectionId);
        }
      } catch (error) {
        console.error(`健康检查失败 ${connectionId}:`, error);
        // 移除有问题的连接器
        const connector = this.connectors.get(connectionId);
        if (connector) {
          await connector.close();
          this.connectors.delete(connectionId);
        }
      }
    }
  }

  // 解密密码（简单实现，实际应用中应使用更安全的方法）
  private async decryptPassword(encryptedPassword: string): Promise<string> {
    // 这里应该实现实际的解密逻辑
    // 目前假设密码是用bcrypt加密的，但实际连接需要明文密码
    // 在实际应用中，应该使用可逆加密算法如AES
    
    // 临时解决方案：假设存储的是明文密码（仅用于开发测试）
    // 实际生产环境中需要实现proper的加密/解密机制
    return encryptedPassword;
  }

  // 清理空闲连接
  async cleanupIdleConnections(): Promise<void> {
    const stats = await this.getAllConnectionStats();
    
    for (const stat of stats) {
      if (stat.poolStatus.idleConnections > 0 && stat.poolStatus.activeConnections === 0) {
        // 如果有空闲连接但没有活跃连接，可以考虑关闭一些空闲连接
        const connector = this.connectors.get(stat.connectionId);
        if (connector) {
          // 这里可以实现更复杂的空闲连接清理逻辑
          console.log(`连接 ${stat.connectionName} 有 ${stat.poolStatus.idleConnections} 个空闲连接`);
        }
      }
    }
  }

  // 获取连接器实例（用于测试）
  getConnectorInstance(connectionId: string): DorisConnector | undefined {
    return this.connectors.get(connectionId);
  }

  // 获取管理器状态
  getManagerStatus(): {
    totalManagedConnections: number;
    healthCheckInterval: number;
    isHealthCheckRunning: boolean;
  } {
    return {
      totalManagedConnections: this.connectors.size,
      healthCheckInterval: this.HEALTH_CHECK_INTERVAL,
      isHealthCheckRunning: this.healthCheckInterval !== null
    };
  }
}

// 导出单例实例
export const dorisConnectionManager = DorisConnectionManager.getInstance();